package cn.changeforyou.web.cloud.webBase.filter;

import cn.changeforyou.web.cloud.webBase.CommonConstant;
import cn.changeforyou.web.cloud.webBase.auth.AuthContainer;
import cn.changeforyou.web.cloud.webBase.auth.AuthModel;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@Slf4j
@Component
@ConditionalOnProperty(prefix = "spring.security.auth", name = "authFilter", havingValue = "gateway")
public class AuthByGatewayFilter implements Filter {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("权限过滤器启动<网关方式>!");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String authStr = httpServletRequest.getHeader(CommonConstant.AUTH_HEADER_NAME);
            try {
                if (StringUtils.isBlank(authStr)) {
                    chain.doFilter(request, response);
                    return;
                }
                String decode = URLDecoder.decode(authStr, "UTF-8");
                AuthModel authModel = objectMapper.readValue(decode, AuthModel.class);
                AuthContainer.setAuthModel(authModel);
                chain.doFilter(request, response);
                AuthContainer.clear();
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            chain.doFilter(request, response);
        }

    }
}